<template>
  <div style="margin:10px 20px">
    <!-- 顶级筛选 -->
    <div class="top-filter">
      <div class="tab-bar">
        <span class="tab" :class="{ 'active': currentTab === 'all' }" @click="changeTab('all')">全部</span>
        <span class="tab" :class="{ 'active': currentTab === 'created' }" @click="changeTab('created')">我创建的</span>
      </div>
      <div class="search-container">
        <div class="search-input-wrapper">
          <input v-model="searchQuery" placeholder="搜索题目" class="search-input" />
          <img src="@/assets/picture/find.png" alt="搜索" class="search-icon" @click="searchQuestions" />
        </div>
        <div v-if="currentTab === 'created' && !isSelectMode" style="display: flex;gap: 10px;">
          <button @click="navigateToEditExam" class="action-button">组卷</button>
          <button 
            v-if="selectedPapers.size > 0"
            @click="batchDelete" 
            class="action-button"
            style="background-color: #ff4d4d;">
            批量删除
          </button>
        </div>
        <button v-else-if="!isSelectMode" @click="navigateToEditExam" class="action-button">组卷</button>
    </div>
     </div>

    <!-- 二级筛选 -->
    <div class="secondary-filters">
      <!-- 方向筛选 -->
     <div class="filter-group">
      <p class="filter-label" style="color: #333333;padding: 0px 12px;">方向:</p>
      <span @click="toggleFilterDirection('all')" :class="{ 'active-filter': selectedFilterDirection === 'all' }">全部</span>
      <span v-for="direction in directions" :key="direction.direction_id" 
            @click="toggleFilterDirection(direction.direction_id)" 
            :class="{ 'active-filter': selectedFilterDirection === direction.direction_id }">
        {{ direction.direction_title }}
      </span>
    </div>

      <!-- 难度筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">难度:</p>
        <span @click="toggleFilterDifficulty('all')" :class="{ 'active-filter': selectedDifficulty === 'all' }">全部</span>
        <span @click="toggleFilterDifficulty('0')" :class="{ 'active-filter': selectedDifficulty === '0' }">简单</span>
        <span @click="toggleFilterDifficulty('1')" :class="{ 'active-filter': selectedDifficulty === '1' }">中等</span>
        <span @click="toggleFilterDifficulty('2')" :class="{ 'active-filter': selectedDifficulty === '2' }">困难</span>
      </div>
    </div>

    <!-- 分页试卷列表 -->
    <ul class="quiz-list">
      <li v-for="quiz in paginatedQuizzes" :key="quiz.id" class="quiz-item">
         <!-- 添加复选框 -->
      <div v-if="currentTab === 'created'" class="checkbox-wrapper">
        <input 
          type="checkbox"
          :checked="selectedPapers.has(quiz.id)"
          @click.stop="toggleSelection(quiz.id)"
          class="paper-checkbox"
        />
      </div>
      <div class="quiz-details">
          <span><strong>{{ quiz.name }}</strong> - {{ quiz.usage }}</span>
          <span>试题数: {{ quiz.questionCount }} | 总分: {{ quiz.totalScore }} | 难度: {{ quiz.difficultyText }}</span>
          <span>更新时间: {{ quiz.updateDate }}</span>
        </div>
        <div class="quiz-buttons">
          <button 
          class="btn action-btn" 
          @click="editQuiz(quiz.id)"  
          v-if="currentTab === 'created'">
          编辑
          </button>
           <!-- 添加删除按钮 -->
        <button 
          v-if="currentTab === 'created'"
          @click.stop="deleteSingle(quiz.id)" 
          class="btn action-btn"
          style="background-color: #ff4d4d;">
          删除
        </button>
          <button 
            v-if="isSelectMode"  
            class="btn action-btn select-mode-btn" 
            @click.stop="selectQuiz(quiz)"   
            :class="{ selected: selectedId === quiz.id }">
            {{ selectedId === quiz.id ? '取消' : '选择' }}
          </button>
        </div>
      </li>
    </ul>
    
    <!-- 分页组件 -->
    <PagiNation
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />

    <router-view v-if="$route.path.includes('create-exam')"></router-view>
  </div>
</template>


<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import PagiNation from '@/components/PagiNation.vue';
import { getQuestionDirections, getPaperHeaders,deletePerper } from '@/services/api'; // 导入获取方向的API
import { defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  components: {
    PagiNation
  },
  props: {
  isSelectMode: {
    type: Boolean,
    default: false
  }
},
  setup(props, { emit }) {
    const router = useRouter();
    const quizzes = ref([]); // 所有试卷数据
    const filteredQuizzes = ref([]); // 筛选后的试卷数据
    const directions = ref([]); // 方向列表
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const totalPages = computed(() => Math.ceil(filteredQuizzes.value.length / itemsPerPage));
    const currentTab = ref('all'); // 顶级筛选的当前标签
    const searchQuery = ref(''); // 搜索关键词
    const selectedFilterDirection = ref('all'); // 方向筛选
    const selectedDifficulty = ref('all'); // 难度筛选
    const selectedQuizzes = ref({});
    const selectedId = ref(null);
    const selectedPapers = ref(new Set());

  const toggleSelection = (paperId) => {
    if (selectedPapers.value.has(paperId)) {
      selectedPapers.value.delete(paperId);
    } else {
      selectedPapers.value.add(paperId);
    }
  };

  const batchDelete = async () => {
      try {
        if (selectedPapers.value.size === 0) return;
        
        await ElMessageBox.confirm(
          `确定删除选中的 ${selectedPapers.value.size} 个试卷吗？`,
          '警告',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        await deletePerper(Array.from(selectedPapers.value).join(','));
        await fetchPaperHeaders();
        selectedPapers.value.clear();
        ElMessage.success("试卷已批量成功删除。");
      } catch (error) {
        // 取消操作自动捕获
      }
    };

  const deleteSingle = async (paperId) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除该试卷吗？',
          '警告',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        await deletePerper(paperId);
        await fetchPaperHeaders();
        ElMessage.success("试卷成功删除。");
      } catch (error) {
        // 取消操作自动捕获
      }
    };

    const selectQuiz = (quiz) => {
      if (props.isSelectMode) {
        if (selectedId.value === quiz.id) {
          // 取消选择
          selectedId.value = null;
          emit('paper-selected', null);
        } else {
          // 选择新试卷
          selectedId.value = quiz.id;
          emit('paper-selected', quiz);
        }
      }
    };
    // 计算分页试卷
    const paginatedQuizzes = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      return filteredQuizzes.value.slice(start, start + itemsPerPage);
    });

    // 页码变化处理
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    // 获取方向列表
const fetchDirections = async () => {
  try {
    const response = await getQuestionDirections();
    if (response.data.status === 1 && response.data.code === 'S0000') {
      directions.value = response.data.data;
    }
  } catch (error) {
    console.error('获取方向列表失败:', error);
  }
};
    // 获取试卷头部数据
const fetchPaperHeaders = async () => {
  try {
    const techId = currentTab.value === 'created' ? localStorage.getItem('id') : null;
    const params = {
      tech_id: techId,
      direction_id: selectedFilterDirection.value !== 'all' 
        ? selectedFilterDirection.value 
        : null,
      difficulty: selectedDifficulty.value !== 'all' 
        ? parseInt(selectedDifficulty.value) // 确保传数字类型
        : null
    };
    const response = await getPaperHeaders(params); // 使用筛选条件调用API
    console.log("API 响应数据:", response.data.data); // 检查数据中是否包含 direction_id

    if (response.data.status === 1 && response.data.code === 'S0000') {
      quizzes.value = response.data.data.map(quiz => ({
        id: quiz.paper_id,
        name: quiz.paper_title,
        difficulty: quiz.difficulty, // 保持数字类型 (0/1/2)
        difficultyText: ['简单', '中等', '困难'][quiz.difficulty], // 新增用于显示的字段
        questionCount: quiz.qs_cnt,
        totalScore: quiz.max_score,
        updateDate: quiz.update_time,
        usageCount: quiz.usage || 0,
        direction_id: quiz.direction_id // 确保包含 direction_id 字段
      }));
      filterQuizzes(); // 更新筛选后的数据
    }
  } catch (error) {
    console.error('获取试卷列表失败:', error);
  }
};

    // 筛选试卷数据
const filterQuizzes = () => {
  filteredQuizzes.value = quizzes.value.filter(quiz => {
    const matchesDifficulty = selectedDifficulty.value === 'all' 
      || quiz.difficulty === parseInt(selectedDifficulty.value); // 使用数字比较
    const matchesSearch = searchQuery.value === '' 
      || quiz.name.includes(searchQuery.value);
    return matchesDifficulty && matchesSearch;
  });
};




    onMounted(() => {
      fetchDirections();
      fetchPaperHeaders();
    });

    return {
      quizzes,
      filteredQuizzes,
      directions,
      currentTab,
      searchQuery,
      selectedFilterDirection,
      selectedDifficulty,
      filterQuizzes,
      currentPage,
      totalPages,
      paginatedQuizzes,
      handlePageChange,
      selectQuiz,
      defineEmits,
      selectedQuizzes,
      selectedId,
      selectedPapers,
      toggleSelection,
      batchDelete,
      deleteSingle,
      changeTab: (tab) => {
        currentTab.value = tab;
        fetchPaperHeaders();
      },
      navigateToEditExam: () => router.push('/teacher/T_exam_bank/create-exam'),
      toggleFilterDirection: (directionId) => {
        selectedFilterDirection.value = directionId;
        fetchPaperHeaders(); // 根据新方向筛选更新列表
      },
      toggleFilterDifficulty: (difficulty) => {
        selectedDifficulty.value = difficulty;
        fetchPaperHeaders(); // 根据新难度筛选更新列表
      },
       editQuiz: (quizId) => {
        router.push(`/edit-exam/${quizId}`);
      },

    };
  }
};
</script>


<style scoped>
body {
  font-family: Arial, sans-serif;
  background-color: #f7f7f7;
  margin: 0;
  padding: 0;
}
.container {
  width: 80%;
  margin: auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.top-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.tab-bar {
  display: flex;
  background-color: white;
  padding: 10px;
}
.tab {
  padding: 10px 20px;
  cursor: pointer;
  transition: background 0.3s ease-in-out;
}
.tab.active {
  border-bottom: 2px solid #244382;
  color: #244382;
  font-weight: bold;
}
.search-container {
  display: flex;
  align-items: center;
  position: relative;
}
.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}
.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 20px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
}
.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}
.action-button {
  background-color: #125aa2;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}
.action-button:hover {
  background-color: #0e4b8a;
}
.new-question-menu {
  width: 66px;
  align-items: center;
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border: 1px solid #ddd;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.new-question-menu span {
  cursor: pointer;
  padding: 5px 0;
  color: gray;
}
.secondary-filters {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  font-size: 14px;
}
.filter-group {
  display: flex;
  gap: 10px;
  align-items: center;
}
.filter-label {
  font-weight: bold;
  color: #666;
}
.secondary-filters span {
  padding: 5px 12px;
  cursor: pointer;
  border-radius: 4px;
  color: #333;
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}
.active-filter {
  color: #ffffff;
  background-color: #eaf4ff;
}
.secondary-filters span:hover:not(.active-filter) {
  background-color: #f0f0f0;
}
.quiz-list {
  list-style-type: none;
  padding: 0;
}
.quiz-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background-color: #ffffff;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.quiz-details {
  flex-grow: 1;
}
.quiz-details span {
  display: block;
}
.quiz-buttons {
  display: flex;
  gap: 10px;
}
.select-mode-btn {
  background-color: #eee !important;
  color: rgb(80, 80, 80) !important;
  border: rgb(95, 95, 95);
}
.select-mode-btn:hover{
  background-color:rgb(212, 212, 212) !important;
}

.select-mode-btn.selected {
  background-color: #4CAF50 !important;
  color: white !important;
}

.quiz-buttons button {
  transition: all 0.3s ease;
}
.action-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.action-btn:hover {
  background-color: #3987d4;
}
.checkbox-wrapper {
  margin-right: 15px;
}

.paper-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 调整按钮间距 */
.quiz-buttons {
  gap: 8px;
}
</style>
